package hflyeer.gitee.com.controller;

import hflyeer.gitee.com.entity.Employee;
import hflyeer.gitee.com.service.SelfService;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller("selfController")
public class SelfController {

    @Resource(name = "selfService")
    SelfService selfService;

    /**
     * /login.do
     * 登录
     *
     * @param request
     * @param response
     */
    public void login(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        Employee loginEmp = selfService.login(username, password);
        if (loginEmp==null){
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            return;
        } else {
            request.getSession().setAttribute("USER",loginEmp);
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }
    }


    /**
     * /logout.do
     * 退出
     *
     * @param request
     * @param response
     */
    public void logout(HttpServletRequest request,HttpServletResponse response) throws IOException {
        request.getSession().removeAttribute("USER");
        response.sendRedirect(request.getContextPath()+"/login.jsp");
    }

     /**
     * /info.do
     * 个人信息
     *
     * @param request
     * @param response
     */
    public void info(HttpServletRequest request,HttpServletResponse response) throws IOException {
        Employee user = (Employee) request.getSession().getAttribute("USER");
        response.sendRedirect(request.getContextPath()+"/info.jsp");
    }


    /**
     * /toChangePassword.do
     * 跳转到修改密码界面
     *
     * @param request
     * @param response
     */
    public void toChangePassword(HttpServletRequest request,HttpServletResponse response) throws IOException {
        response.sendRedirect(request.getContextPath()+"/change_password.jsp");
    }



     /**
     * /changePassword.do
     * 修改密码
     *
     * @param request
     * @param response
     */
    public void changePassword(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        String pass = request.getParameter("pass");
        String pass1 = request.getParameter("pass1");
        if (pass.equals(pass1)){
            Employee user = (Employee) request.getSession().getAttribute("USER");
            int id = user.getId();
            selfService.changePassword(pass,id);
            request.getRequestDispatcher("/logout.do").forward(request,response);
        }else {
            request.getRequestDispatcher("/toChangePassword.do").forward(request,response);
        }
    }



}
